/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.vdr.channel.editor.container;

import java.awt.Point;
import java.awt.dnd.DnDConstants;

import javax.swing.DefaultListModel;
import javax.swing.tree.DefaultMutableTreeNode;

import de.renier.vdr.channel.ChannelElement;

/**
 * DefaultListTransferHandler
 * 
 * @author <a href="mailto:editor@renier.de">Renier Roth</a>
 */
public class DefaultListTransferHandler extends AbstractListTransferHandler {

  public DefaultListTransferHandler(DNDList list, int action) {
    super(list, action, true);
  }

  public boolean canPerformAction(DNDList target, DefaultMutableTreeNode draggedNode, int action, Point location) {

    // get channelElement
    if (draggedNode.getUserObject() instanceof ChannelElement) {
      ChannelElement channelElementSource = (ChannelElement) draggedNode.getUserObject();
      if (!channelElementSource.isRadioOrTelevisionOrService() && !channelElementSource.isCategory()) { return (false); }
    }

    if (action == DnDConstants.ACTION_MOVE) { return (true); }
    return (false);
  }

  public boolean executeDrop(DNDList target, DefaultMutableTreeNode draggedNode, int newPosition, int action) {

    if (action == DnDConstants.ACTION_MOVE) {
      // special for treenode, we remove always the parent
      draggedNode.removeFromParent();
      DefaultListModel listModel = (DefaultListModel) target.getModel();
      if (listModel.capacity() > 0 && newPosition > -1) {
        listModel.add(newPosition, draggedNode);
      } else {
        listModel.addElement(draggedNode);
      }
      return (true);
    }
    return (false);
  }

  /*
   * (non-Javadoc)
   * 
   * @see de.renier.vdr.channel.editor.tree.AbstractListTransferHandler#afterDrop(javax.swing.tree.DefaultMutableTreeNode,
   *      int)
   */
  public void afterDrop(DNDList dndList, DefaultMutableTreeNode draggedNode, int action) {
    if (action == DnDConstants.ACTION_MOVE) {
      DefaultListModel listModel = (DefaultListModel) dndList.getModel();
      listModel.removeElement(draggedNode);
    }
  }
}